package com.oss.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Page;
import com.oss.model.*;
import com.oss.utils.EmojiUtils;
import com.oss.utils.ZxingKit;
import com.oss.view.InvokeResult;

import java.util.*;

import static com.oss.utils.constants.FolderLocation.*;

public class UsersService {
    private static final Users usersDao = new Users().dao();
    private static final Orders ordersDao = new Orders().dao();
    private static final Dealer dealerDao = new Dealer().dao();
    private static final Area areaDao = new Area().dao();

    static Log log = Log.getLog(UsersService.class);


    /**
     * 导出核销店员账号
     */
    public InvokeResult export() {
        ArrayList<Map<String, Object>> rows = CollUtil.newArrayList();

        List<Dealer> dealerList = dealerDao.find("SELECT * FROM dealer");
        if (dealerList.size() > 0) {

            for (Dealer dealer : dealerList) {

                Map<String, Object> item = new LinkedHashMap<>();
                item.put("省", areaDao.findById(dealer.getProvince()).getName());
                item.put("市", areaDao.findById(dealer.getCity()).getName());
                item.put("经销商名称", dealer.getName());
                String account = "YJY" + RandomUtil.randomNumbers(5);
                String password = RandomUtil.randomNumbers(8);
                item.put("账号", account);
                item.put("密码", password);
                rows.add(item);

                Employee employee = new Employee();
                employee.setAccount(account);
                employee.setPassword(SecureUtil.md5(password));
                employee.setDealerId(dealer.getId());
                employee.setIsEnable(1);
                employee.save();

            }
        }


        if (rows.size() == 0) {
            return InvokeResult.failure("没数据");
        }

        String basePath = LOCAL_PATH + EXCEL;
        String suffixName = ".xlsx";//后缀名
        String fileName = DateUtil.format(new Date(), "yyyyMMddHHmmss") + suffixName;


        // 通过工具类创建writer
        ExcelWriter writer = ExcelUtil.getWriter(basePath + fileName);

        // 合并单元格后的标题行，使用默认标题样式
        writer.merge(rows.get(0).size() - 1, "经销商核销登录账号密码表");
        // 一次性写出内容，使用默认样式
        writer.write(rows);
        // 关闭writer，释放内存
        writer.close();
        return InvokeResult.success();
    }

    /**
     * 根据openid找用户
     *
     * @param openId
     * @return
     */
    public Users findByOpendId(String openId) {
        return usersDao.findFirst("SELECT * FROM users WHERE open_id=?", openId);
    }

    /**
     * 用户注册
     *
     * @return
     */
    public InvokeResult register(String userId, String name, Integer gender, String mobile, String province, String city, String region, Integer dealerId) {
        if (Validator.isEmpty(userId)) {
            log.error("userId is null");
            return InvokeResult.failure("userId is null");
        }

        Users users = usersDao.findById(userId);
        if (users == null) {
            return InvokeResult.failure("用户不存在");
        }

        if (!Validator.isMobile(mobile)) {
            return InvokeResult.failure("请输入正确的手机号码");
        }

        users.setMobile(mobile);
        users.setName(name);
        users.setGender(gender);
        users.setProvince(province);
        users.setCity(city);
        users.setRegion(region);
//        users.setDetailAddress(detailAddress);
        users.setDealerId(dealerId);
        users.setRegDealerId(dealerId);
        String memberCode = users.getMemberCode();
        String saveImgFilePath = LOCAL_PATH + USER_QR + memberCode + ".png";
        ZxingKit.encode(memberCode, BarcodeFormat.QR_CODE, 0, ErrorCorrectionLevel.H, "png", 250, 250,
                saveImgFilePath);
        users.setQrCodeUrl(USER_QR + memberCode + ".png");
        users.update();
        return getUserInfo(userId);
    }

    /**
     * 修改用户个人信息
     *
     * @return
     */
    public InvokeResult updateUserInfo(String userId, String mobile, String province, String city, String region, String detailAddress) {
        if (Validator.isEmpty(userId)) {
            log.error("userId is null");
            return InvokeResult.failure("userId is null");
        }

        Users users = usersDao.findById(userId);
        if (users == null) {
            return InvokeResult.failure("用户不存在");
        }
        users.setMobile(mobile);
        users.setProvince(province);
        users.setCity(city);
        users.setRegion(region);
        users.setDetailAddress(detailAddress);
        users.update();
        return InvokeResult.success(users);
    }

    /**
     * 获取用户个人信息
     *
     * @param userId
     * @return
     */
    public InvokeResult getUserInfo(String userId) {
        if (Validator.isEmpty(userId)) {
            log.error("userId is null");
            return InvokeResult.failure("userId is null");
        }
        Users users = usersDao.findById(userId);
        if (users != null) {
            users.setQrCodeUrl(NETWORK_PATH + users.getQrCodeUrl());
            users.setNickname(EmojiUtils.emojiRecovery2(users.getNickname()));
            String str = "C";
            if (users.getLevelId() == 2) {//高级会员
                str = "G";
            }
            users.setMemberCode(str + users.getMemberCode());
        }
        return InvokeResult.success(users);
    }

    /**
     * 获取用户个人信息
     *
     * @param memberCode
     * @return
     */
    public InvokeResult getUserInfoByMemberCode(String memberCode) {
        if (Validator.isEmpty(memberCode)) {
            log.error("memberCode is null");
            return InvokeResult.failure("memberCode is null");
        }
        Users users = usersDao.findFirst("SELECT * FROM users WHERE member_code=?", memberCode);
        if (users != null) {
            users.setNickname(users.getName());
            users.setQrCodeUrl(NETWORK_PATH + users.getQrCodeUrl());
            Integer regDealerId = users.getRegDealerId();
            String regDealerName = "";
            Dealer dealer = dealerDao.findById(regDealerId);
            if (dealer != null) {
                regDealerName = dealer.getName();
            }
            users.put("reg_dealer_name", regDealerName);
        }
        return InvokeResult.success(users);
    }

    public InvokeResult getUserOrderList(String userId, Integer pageNumber, Integer pageSize) {
        Page<Orders> paginate = ordersDao.paginate(pageNumber, pageSize, "SELECT * ", " FROM `orders` WHERE users_id=?", userId);
        return InvokeResult.success(paginate);
    }

}
